package smashedapples.google.feeds
{
	import com.adobe.serialization.json.JSON;
	
	import mx.rpc.AsyncToken;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;
	
	import smashedapples.core.Command;
	import smashedapples.core.Config;
	import smashedapples.core.Request;
	
	public class GoogleFeedRequest extends Request
	{
		public function GoogleFeedRequest(command: Command , url : String, responseHandler : Function):void
		{
			super(command);	
			this.url = url;
			this.responseHandler = responseHandler;
		}
		
		public var responseHandler : Function;
		
		public var url : String;
		
		public function send(showBusyCursor:Boolean=false):AsyncToken
		{
			var service : HTTPService = new HTTPService(null,"DefaultHTTP");
				service.url = Config.Static.googleFeedUrl; 
				service.method = "GET";
				service.resultFormat = "text";
				service.useProxy = false;
				service.showBusyCursor = showBusyCursor;
				
				service.addEventListener(ResultEvent.RESULT, resultHandler );
				
			var params : Object = {};
				params["q"] = encodeURI(this.url);
				params["v"] = "1.0";
				
			return service.send(params);
		}
		
		
		private function resultHandler(event:ResultEvent):void
		{
			var rawData:String = String(event.result);
			var obj:Object = (JSON.decode(rawData) as Object);
			
			var response : GoogleFeedResponse = new GoogleFeedResponse(null);
				response.responseStatus = Number( obj["responseStatus"] );
				response.responseDetails = Object( obj["responseDetails"] );
				response.feed = new GoogleFeedVO( Object( obj["responseData"]["feed"]) );
			
			
			this.responseHandler(response);
	
		}
		

	}
}